package com.mySpringMvc.web.servlet.mvc.method.annotation;

import com.mySpringMvc.context.WebApplicationContext;
import com.mySpringMvc.web.method.HandlerMethod;
import com.mySpringMvc.web.servlet.HandlerExecutionChain;
import com.mySpringMvc.web.servlet.HandlerInterceptor;
import com.mySpringMvc.web.servlet.HandlerMapping;
import com.mySpringMvc.web.servlet.mvc.method.RequestMappingInfo;
import jakarta.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Map;

/**
 * @program: mySSM
 * @description: 服务与@RequestMapping注解的处理器映射器，常见的处理器映射器之一
 * @author:wjp
 * @create: 2025-02-13 18:14
 **/
public class RequestMappingHandlerMapping implements HandlerMapping {

    /**
     * 存储请求映射信息和对应的执行器方法
     * 项目初始化时初始化该map
     */
    private Map<RequestMappingInfo, HandlerMethod> map;

    public RequestMappingHandlerMapping(Map<RequestMappingInfo, HandlerMethod> map) {
        this.map = map;
    }

    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        HandlerExecutionChain handlerExecutionChain = new HandlerExecutionChain();
        // 从map中获取对应的handlerMethod
        RequestMappingInfo requestMappingInfo = new RequestMappingInfo();
        requestMappingInfo.setRequestURI(request.getServletPath());
        requestMappingInfo.setMethod(request.getMethod());
        handlerExecutionChain.setHandler(map.get(requestMappingInfo));
        // 从web容器中获取拦截器
        WebApplicationContext webApplicationContext = (WebApplicationContext) request.getServletContext().getAttribute("webApplicationContext");
        List<HandlerInterceptor> interceptorList = (List<HandlerInterceptor>) webApplicationContext.getBean("interceptorList");
        handlerExecutionChain.setIntercepterList(interceptorList);
        return handlerExecutionChain;
    }
}
